import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/routes/routes.dart';
import 'package:sainbainu/common/services/jpush.dart';
import 'package:sainbainu/common/services/user.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/utils/util.dart';

import 'index.dart';

class AccountSecurityController extends GetxController {
  AccountSecurityController();

  final state = AccountSecurityState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();

    state.obscureMobile.value = Util.obscurePhoneNumber(
      UserService.to.accountInfo.value.mobile ?? '',
    );
    state.isRealed.value = UserService.to.accountInfo.value.realFlag == 1;
    state.isOfficial.value = UserService.to.accountInfo.value.officialFlag == 1;

    ever(UserService.to.accountInfo, (accountInfo) {
      state.obscureMobile.value = Util.obscurePhoneNumber(
        accountInfo.mobile ?? '',
      );
      state.isRealed.value = accountInfo.realFlag == 1;
      state.isOfficial.value = accountInfo.officialFlag == 1;
    });
    JpushService.to.getRegistrationID().then((rid) {
      state.registrationId.value = rid ?? '';
    });
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  /// 跳转到实名认证
  toRealNameAuth() {
    Get.toNamed(AppRoutes.realNameAuth);
  }

  /// 跳转到官方认证
  toOfficialAuth() {
    Get.toNamed(AppRoutes.officialAuth);
  }

  /// 复制 registrationId
  Future<void> handleCopy() async {
    await Clipboard.setData(
      ClipboardData(text: state.registrationId.value),
    );
    LoadingUtil.showSuccess('已复制');
  }
}
